package com.yiren.dbaa.module.practice_set.site.model;

import android.app.Activity;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.yiren.backstage.config.api.LoadConfigApi;
import com.yiren.backstage.config.bean.device.UserParamConfigBean;
import com.yiren.backstage.currency.constant.DbConstant;
import com.yiren.backstage.currency.entity.LineInfoEntity;
import com.yiren.backstage.currency.entity.MapEntity;
import com.yiren.backstage.currency.entity.SiteEntity;
import com.yiren.backstage.currency.utils.FileUtil;
import com.yiren.dbaa.constant.AddressConstant;
import com.yiren.dbaa.currency.api.CommonCallBack;
import com.yiren.dbaa.net.oss.IOssFileOperationApi;
import com.yiren.dbaa.net.interf.OssFileCallback;
import com.yiren.dbaa.net.oss.impl.OssFileOperationApiImpl;
import com.yiren.dbaa.module.practice_set.site.bean.BaseRuleNewBean;
import com.yiren.dbaa.module.practice_set.site.bean.ModifyValBean;
import com.yiren.dbaa.module.practice_set.site.bean.PersonDownLoadDataBean;
import com.yiren.dbaa.module.practice_set.site.contract.SiteRuleContract;
import com.yiren.dbaa.net.OkHttpUtils;
import com.yiren.dbaa.net.bean.BaseResponseBean;
import com.yiren.dbaa.net.bean.TestBaseBean;
import com.yiren.dbaa.net.interf.StringCallback;
import com.yiren.dbaa.util.ZipUtils;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author lwb
 * @date : 2022/9/20 14:40
 * @description: 考场规则首页Model
 */
public class SiteRuleModel implements SiteRuleContract.Model {

    private Gson gson;

    private Activity activity;

    private IOssFileOperationApi iOssFileOperationApi;

    public SiteRuleModel(Activity activity) {
        gson = new Gson();
        this.activity = activity;
        iOssFileOperationApi = new OssFileOperationApiImpl(activity);
    }

    @Override
    public void getSiteRuleFromServer(String id,boolean isPublic,CommonCallBack callBack) {
        OkHttpUtils.getInstance().getStringByAsync(activity, AddressConstant.loadRuleByUser("?user_id=" + id), new StringCallback() {
            @Override
            public void getString(String result) {
                TestBaseBean<List<SiteEntity>> testBaseBean = gson.fromJson(result, new TypeToken<TestBaseBean<List<SiteEntity>>>() {
                }.getType());
                if (testBaseBean.isSuccess()) {
                    if (testBaseBean.getData() != null && !isPublic ){
                        List<SiteEntity> siteList = new ArrayList<>();
                        for (int i = 0; i < testBaseBean.getData().size(); i++){
                            if (testBaseBean.getData().get(i).getState() == 1){
                               siteList.add(testBaseBean.getData().get(i));
                            }
                        }
                        callBack.success(siteList);
                    }else {
                        callBack.success(testBaseBean.getData());
                    }

                } else {
                    callBack.fail("数据请求错误!");
                }
            }

            @Override
            public void getFail() {
                callBack.fail("数据请求失败!");
            }
        });
    }

    @Override
    public List<SiteEntity> siteRuleHomedataMerge(BaseRuleNewBean baseRuleNewBean,List<SiteEntity> localSites, List<SiteEntity> serverSites) {
        UserParamConfigBean userParamConfigBean = LoadConfigApi.loadUserParamConfig(activity);
        for (SiteEntity localSite : localSites) {
            boolean exist = false;
            for (int i = 0; i < serverSites.size(); i++) {
                SiteEntity serverSite = serverSites.get(i);
                //本地存在 以本地数据为准
                if (localSite.getSiteCode().equals(serverSite.getSiteCode())) {
                    if (localSite.getRuleVer() > 0)
                    localSite.setRuleVerLast(serverSite.getRuleVer());
                    //判断版本是否可更新，教练：判断规则版本  合伙人：判断基础数据版本
                    if (userParamConfigBean.isPartner()) {
                        if (localSite.getBaseVer() < baseRuleNewBean.getVer())
                            localSite.setUpdate(true);
                            localSite.setBaseVerLast(baseRuleNewBean.getVer());
                            localSite.setUpdateDetails(baseRuleNewBean.getUpdateDetails());
                    } else {
                        if (localSite.getRuleVer() < serverSite.getRuleVer()){
                            localSite.setUpdateDetails(serverSite.getUpdateDetails());
                            localSite.setUpdate(true);
                        }
                    }
                    //判断本地文件是否存在
                    if (FileUtil.exists(DbConstant.App_Main_Directory + userParamConfigBean.getUserInfo().getId() + "/my/" + localSite.getSiteCode() + "/" + DbConstant.GRADE_DATA_NAME))
                        localSite.setDownLoad(true);
                    serverSites.set(i, localSite);
                    exist = true;
                    break;
                }
            }
            //新增
            if (!exist) {
                localSite.setDownLoad(true);
                serverSites.add(localSite);
            }
        }
        return serverSites;
    }


    @Override
    public void loadBaseDataDownLoadUrl(float baseVer, CommonCallBack commonCallBack) {
        Map<String, Object> map = new HashMap<>();
        map.put("siteCode", baseVer);
        //获取数据下载地址
        OkHttpUtils.getInstance().postMapByAsync(activity, AddressConstant.getDownloadExaminationUrl(), map, new StringCallback() {
            @Override
            public void getString(String result) {
                BaseResponseBean<PersonDownLoadDataBean> responseBean = gson.fromJson(result, new TypeToken<BaseResponseBean<PersonDownLoadDataBean>>() {
                }.getType());
                if (responseBean.getError() != null) {
                    commonCallBack.fail(responseBean.getError().toString());
                    return;
                }
                if (responseBean.getResult() == null) {
                    commonCallBack.fail("下载地址为空！");
                    return;
                }
                commonCallBack.success(responseBean.getResult());
            }
        });
    }

    @Override
    public void downLoadBaseData(SiteEntity site, CommonCallBack callBack) {
        String objectKey = site.getBaseVer() + ".zip";
        UserParamConfigBean userParamConfigBean = LoadConfigApi.loadUserParamConfig(activity);
        String sdkDownUrl = AddressConstant.App_Main_Directory() + userParamConfigBean.getUserInfo().getId() + "/my/" + site.getSiteCode() + "/";
        iOssFileOperationApi.downLoadFile(AddressConstant.DJ_BASE_RULE_DATA, objectKey, sdkDownUrl, objectKey, new OssFileCallback() {
            @Override
            public void success(String result) {
                try {
                    File file = new File(sdkDownUrl, objectKey);
                    ZipUtils.decompressFile(file, sdkDownUrl);
                    //删除 zip 文件
                    file.delete();
                    callBack.success(result);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void fail(String error) {
                callBack.fail(error);
            }
        });
    }

    @Override
    public void downLoadModifyVal(int pUserId, String siteCode, float ruleVer,CommonCallBack callBack) {
        UserParamConfigBean userParamConfigBean = LoadConfigApi.loadUserParamConfig(activity);
        int cUserId;
        if (userParamConfigBean.isPartner()){
           pUserId = userParamConfigBean.getUserInfo().getId();
            cUserId = userParamConfigBean.getUserInfo().getId();
        }else {
            pUserId = userParamConfigBean.getUserInfo().getpUserId();
            cUserId = userParamConfigBean.getUserInfo().getId();
        }
        OkHttpUtils.getInstance().getStringByAsync(activity, AddressConstant.loadExamRuleUpdateDetails("?cUserId="+cUserId+"&siteCode="+siteCode+"&ruleVer="+ruleVer+"&pUserId="+pUserId), new StringCallback() {
            @Override
            public void getString(String result) {
                TestBaseBean<List<ModifyValBean>>  testBaseBean = gson.fromJson(result, new TypeToken<TestBaseBean<List<ModifyValBean>>>() {}.getType());
                if (testBaseBean.isSuccess()){
                    if (testBaseBean.getData().size()==0){
                        callBack.success(new ModifyValBean());
                    }else {
                        callBack.success(testBaseBean.getData().get(0));
                    }

                }else {
                    callBack.fail("数据请求错误!");
                }
            }

            @Override
            public void getFail() {
                callBack.fail("数据请求失败!");
            }
        });
    }

    @Override
    public void getNewBaseRule(CommonCallBack callBack) {
        OkHttpUtils.getInstance().getStringByAsync(activity, AddressConstant.loadNewestBase(), new StringCallback() {
            @Override
            public void getString(String result) {
                TestBaseBean<List<BaseRuleNewBean>>  testBaseBean = gson.fromJson(result,new TypeToken<TestBaseBean<List<BaseRuleNewBean>>>() {}.getType());
                if (testBaseBean.isSuccess()){
                    callBack.success(testBaseBean.getData());
                }
            }
            @Override
            public void getFail() {
                callBack.fail("数据请求失败!");
            }
        });

    }

    @Override
    public void getLineInfoBySiteCode(String siteCode,int userId, CommonCallBack callBack) {
        OkHttpUtils.getInstance().getStringByAsync(activity, AddressConstant.loadLineinfoBySitecode("?siteCode="+siteCode+"&userId="+userId), new StringCallback() {
            @Override
            public void getString(String result) {
                TestBaseBean<List<LineInfoEntity>>  testBaseBean = gson.fromJson(result,new TypeToken<TestBaseBean<List<LineInfoEntity>>>() {}.getType());
                if (testBaseBean.isSuccess()){
                    callBack.success(testBaseBean.getData());
                }
            }
        });
    }

    @Override
    public void getMapBySiteCode(String siteCode,int userId, CommonCallBack callBack) {
        OkHttpUtils.getInstance().getStringByAsync(activity, AddressConstant.loadMapBySitecode("?siteCode="+siteCode+"&userId="+userId), new StringCallback() {
            @Override
            public void getString(String result) {
                TestBaseBean<List<MapEntity>>  testBaseBean = gson.fromJson(result,new TypeToken<TestBaseBean<List<MapEntity>>>() {}.getType());
                if (testBaseBean.isSuccess()){
                    callBack.success(testBaseBean.getData());
                }
            }
        });
    }
}
